import React, { PureComponent } from 'react';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Col,
  Row,
  Input,
  Select,
  Modal,
  Spin,
  InputNumber,
  message,
  Divider,
  Table,
  Popconfirm,
  DatePicker,
} from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import moment from 'moment';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import HOCSelect from '@/components/AntDesign/Select';
import styles from './style.less';

const { Option } = Select;
const FormItem = Form.Item;
const { confirm } = Modal;
const { MonthPicker } = DatePicker;
@Form.create()
@connect(({ injuryware, loading }) => ({
  injuryware,
  loading: loading.effects['injuryware/custName'],
}))
class AdvancedForm extends PureComponent {
  // 组件内所有数据的初始状态
  state = {
    visible: false,
    showFlag: '1',
    mustFlag: true, // 是否必填
    btnState1: false, // 提交按钮状态
    useFeeRatioFlag: true,
    listIndex: 0,
  };

  componentDidMount() {
    const { form, dispatch } = this.props;
    form.setFieldsValue({
      doneFlag: '1',
    });
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['YES_NO_FLAG'],
    }).then(res => {
      dispatch({
        type: 'injuryware/updateModelData',
        payload: {
          yesNoFlag: res.YES_NO_FLAG,
        },
      });
    });
    this.getBigName();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'injuryware/updateModelData',
      payload: {
        ratioList: [],
      },
    });
  }

  getBigName = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'injuryware/getBigName',
      payload: {
        accoStatus: 2,
      },
    });
  };

  custName = name => {
    const { dispatch } = this.props;
    dispatch({
      type: 'injuryware/custName',
      payload: {
        name,
      },
    });
  };

  // 取消
  cancel = () => {
    router.goBack();
  };

  onCancel = () => {
    this.setState({
      visible: false,
    });
  };

  // 处理入参格式
  handleInparam = values => {
    const temp = values;
    Object.keys(values).forEach(key => {
      if (key === 'custList' && values[key]) {
        temp[key] = JSON.parse(
          JSON.stringify(values[key])
            .replace(new RegExp('key', 'g'), 'mdCustId')
            .replace(new RegExp('label', 'g'), 'mdCustName')
        );
      }
    });
    const {
      injuryware: { insAccoName, ratioList },
    } = this.props;
    temp.insAccoName = insAccoName;
    if (ratioList.length) temp.ratioList = ratioList;
    temp.doneFlag = Number(values.doneFlag);
    temp.useTaxFlag = Number(values.useTaxFlag);
    const { showFlag, useFeeRatioFlag } = this.state;
    if (showFlag === '2') {
      if (values.injSecAccoCode) {
        delete temp.injSecAccoCode;
      }
      if (values.feeRatio) {
        delete temp.feeRatio;
      }
      if (values.ratioList) {
        delete temp.ratioList;
      }
    }
    if (useFeeRatioFlag) {
      delete temp.floatFeeRatio;
    } else {
      delete temp.feeRatio;
    }
    return temp;
  };

  // 提交并启用
  showModal = () => {
    const { form, dispatch } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const params = this.handleInparam(values);
        const confirmReference = confirm({
          title: '提示',
          icon: <ExclamationCircleOutlined />,
          content: '启用后，"所属大库、二级户编码、关联客户"将不可修改，确定启用吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            confirmReference.update({
              okButtonProps: true,
            });
            return new Promise(resolve => {
              dispatch({
                type: 'injuryware/submitEnable',
                payload: {
                  ...params,
                },
              }).then(res => {
                if (res.success) {
                  router.goBack();
                } else {
                  message.warning(res.message || '服务端错误');
                }
                resolve();
              });
            });
          },
          onCancel() {},
        });
      }
    });
  };

  // 表单检测 并 提交
  submitAll = () => {
    const { form, dispatch } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const params = this.handleInparam(values);
        this.setState({
          btnState1: true,
        });
        this.setState({
          btnState1: true,
        });
        dispatch({
          type: 'injuryware/submitAll',
          payload: {
            ...params,
          },
        }).then(res => {
          if (res.success) {
            router.goBack();
          } else {
            message.warning(res.message || '服务端错误');
          }
          this.setState({
            btnState1: false,
          });
        });
      }
    });
  };

  remove = keys => {
    const {
      dispatch,
      injuryware: { ratioList },
    } = this.props;
    if (keys.key) {
      const newData = ratioList.filter(item => item.key !== keys.key);
      dispatch({
        type: 'injuryware/updateModelData',
        payload: {
          ratioList: newData,
        },
      });
    }
  };

  bigChange = (value, item) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'injuryware/updateModelData',
      payload: {
        insAccoName: item.props.children,
      },
    });
  };

  accountCompletion = value => {
    let mustFlag;
    if (String(value) === '1') {
      mustFlag = true;
    } else {
      mustFlag = false;
    }
    this.setState({
      showFlag: value,
      mustFlag,
    });
  };

  useFeeRatio = val => {
    let flag;
    if (String(val) === '1') {
      flag = true;
    } else {
      flag = false;
    }
    this.setState({ useFeeRatioFlag: flag });
  };

  // 开始年月发生改变时
  dataTimelist = (date, record, index) => {
    const {
      injuryware: { ratioList },
      dispatch,
    } = this.props;
    const newData = ratioList.map(item => ({ ...item }));
    newData.map((item, idx) => {
      const newItem = item;
      if (Number(index) === idx) {
        newItem.beginYm = moment(date).format('YYYYMM');
      }
      return true;
    });
    dispatch({
      type: 'injuryware/updateModelData',
      payload: {
        ratioList: newData,
      },
    });
  };

  disabledDate = startValue => {
    const {
      injuryware: { ratioList },
    } = this.props;
    if (!startValue) {
      return false;
    }
    if (ratioList.length === 1) {
      return false;
    }
    // 使用第二时间段开始时间+1月作为限制值
    return (
      startValue.valueOf() <
      moment(ratioList[1].beginYm, 'YYYY-MM')
        .add(1, 'months')
        .valueOf()
    );
  };

  // 新增
  addList = () => {
    const { listIndex } = this.state;
    const {
      injuryware: { ratioList },
      dispatch,
    } = this.props;
    // 复制列表
    const newData = ratioList.map(item => ({ ...item }));
    let tempDate;
    // if (!newData?.[0]?.beginYm || !newData[0].beginYm) {

    // 取数组第一项
    const firstNewData = newData?.[0];
    // 数组第一项已经有值
    if (firstNewData?.beginYm) {
      // 默认开始时间加1年，月份1月
      tempDate = moment(firstNewData.beginYm)
        .add(1, 'y')
        .month(0)
        .format('YYYYMM');
    } else {
      // 没有值取当前日期
      tempDate = moment(new Date()).format('YYYYMM');
    }
    newData.unshift({
      key: `list_${listIndex}`,
      beginYm: tempDate,
      floatFeeRatio: null,
    });
    this.setState({ listIndex: listIndex + 1 });
    dispatch({
      type: 'injuryware/updateModelData',
      payload: {
        ratioList: newData,
      },
    });
  };

  dataSlist = (e, record, index) => {
    const {
      dispatch,
      injuryware: { ratioList },
    } = this.props;
    const newData = ratioList.map(item => ({ ...item }));
    newData.forEach((item, idx) => {
      const newItem = item;
      if (Number(index) === idx) {
        newItem.floatFeeRatio = e;
      }
    });
    dispatch({
      type: 'injuryware/updateModelData',
      payload: {
        ratioList: newData,
      },
    });
  };

  // 渲染函数
  render() {
    const {
      form: { getFieldDecorator },
      injuryware: { comList, bigResult, yesNoFlag, ratioList },
      loading,
    } = this.props;
    const { btnState1, visible, showFlag, mustFlag, useFeeRatioFlag } = this.state;

    const comOption = comList.map(value => (
      <Option key={value.mdCustId} value={value.mdCustId} title={value.name}>
        {value.name}
      </Option>
    ));
    const bigChildren = bigResult.map(email => (
      <Option key={email.insAccoId}>{email.accoName}</Option>
    ));
    const columns = [
      {
        title: '开始年月', // disabled={index == (this.state.dataSource.length - 1)}disabled={record.updateFlag== 2?true:false}
        dataIndex: 'beginYm',
        key: 'beginYm',
        width: '15%',
        render: (text, record, index) => (
          <MonthPicker
            placeholder="请选择"
            format="YYYY-MM"
            style={{ width: '100%' }}
            value={text ? moment(text, 'YYYY-MM') : null}
            disabled={index !== 0}
            disabledDate={startValue => this.disabledDate(startValue, record.rangeDate)}
            allowClear={false}
            onChange={date => this.dataTimelist(date, record, index)}
          />
        ),
      },
      {
        title: '工伤比例(%)', // defaultValue={index == (this.state.dataSource.length - 1) ? record.ratioVal : ''}
        dataIndex: 'floatFeeRatio',
        key: 'floatFeeRatio',
        width: '15%',
        render: (text, record, index) => (
          <InputNumber
            value={text}
            min={0}
            max={99.9999}
            precision={4}
            placeholder="请输入工伤比例"
            style={{ width: '100%' }}
            onChange={e => this.dataSlist(e, record, index)}
          />
        ),
      },
      {
        title: '操作',
        key: 'action',
        width: '15%',
        render: (text, record, index) =>
          index !== 0 ? null : (
            <span>
              <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record)}>
                <a>删除</a>
              </Popconfirm>
            </span>
          ),
      },
    ];
    return (
      <Form layout="vertical">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Card title={<span>工伤二级户信息</span>} bordered={false}>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="所属大库">
                  {getFieldDecorator('insAccoId', {
                    rules: [{ required: true, message: '请输入所属大库' }],
                  })(
                    <HOCSelect
                      style={{ width: '100%' }}
                      placeholder="请选择大库名称"
                      onChange={this.bigChange}
                      allowClear
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {bigChildren}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="二级户名称">
                  {getFieldDecorator('injSecAccoName', {
                    rules: [{ required: true, pattern:/^(?!\.)[^\\/:*?"<>|]{1,255}$/,message: '文件名不能包含下列任何字符  \\  /  :  *   ?  "  <  >  |'}],
                  })(<Input placeholder="请输入二级户名称" maxLength={25} />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="是否使用基准费率">
                  {getFieldDecorator('useTaxFlag', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <HOCSelect
                      style={{ width: '100%' }}
                      placeholder="请选择"
                      onChange={this.useFeeRatio}
                      allowClear
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {yesNoFlag.map(value => (
                        <Option value={value.itemCode} key={value.itemCode}>
                          {value.itemName}
                        </Option>
                      ))}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="是否开户完成">
                  {getFieldDecorator('doneFlag', {})(
                    <HOCSelect
                      style={{ width: '100%' }}
                      placeholder="请选择是否开户完成"
                      onChange={this.accountCompletion}
                      allowClear
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {yesNoFlag.map(value => (
                        <Option value={value.itemCode} key={value.itemCode}>
                          {value.itemName}
                        </Option>
                      ))}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col
                xl={{ span: 8 }}
                lg={{ span: 8 }}
                md={{ span: 8 }}
                sm={24}
                className={showFlag === '1' ? 'show' : 'hide'}
              >
                <FormItem label="二级户编码">
                  {getFieldDecorator('injSecAccoCode', {
                    rules: [
                      {
                        required: mustFlag,
                        message: '请输入二级户编码(纯数字)',
                        pattern: /^[0-9]*$/,
                      },
                    ],
                  })(
                    <InputNumber
                      maxLength={12}
                      placeholder="请输入纯数字"
                      style={{ width: '100%' }}
                    />
                  )}
                </FormItem>
              </Col>
              <Col
                xl={{ span: 8 }}
                lg={{ span: 8 }}
                md={{ span: 8 }}
                sm={24}
                className={showFlag === '1' && useFeeRatioFlag ? 'show' : 'hide'}
              >
                <FormItem label="基准费率(%)">
                  {getFieldDecorator('feeRatio', {
                    rules: [
                      {
                        required: useFeeRatioFlag && mustFlag,
                        message: '请输入小数点不超过4位基准费率',
                        pattern: /^[0-9]{0,7}(\.[0-9]{1,4})?$/,
                      },
                    ],
                  })(
                    // <InputNumber
                    //   min={0.0001}
                    //   max={99.9999}
                    //   precision={4}
                    //   placeholder="请输入基准费率"
                    //   style={{ width: '100%' }}
                    // />
                    <InputNumber placeholder="请输入基准费率" style={{ width: '100%' }} />
                  )}
                </FormItem>
              </Col>
              <Col
                xl={{ span: 8 }}
                lg={{ span: 8 }}
                md={{ span: 8 }}
                sm={24}
                className={showFlag === '1' && !useFeeRatioFlag ? 'show' : 'hide'}
              >
                <FormItem label="浮动费率(%)">
                  {getFieldDecorator('floatFeeRatio', {
                    rules: [
                      {
                        required: showFlag === '1' && !useFeeRatioFlag,
                        message: '请输入浮动费率',
                      },
                    ],
                  })(
                    <InputNumber
                      min={0}
                      max={99.9999}
                      precision={4}
                      placeholder="请输入浮动费率"
                      style={{ width: '100%' }}
                    />
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="关联客户名称">
                  {getFieldDecorator('custList', {
                    rules: [{ required: true, message: '请选择关联客户' }],
                  })(
                    <HOCSelect
                      allowClear
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      mode="multiple"
                      labelInValue
                      onSearch={this.custName}
                      style={{ width: '100%' }}
                      placeholder="请输入关键字搜索关联客户名称"
                      notFoundContent={loading ? <Spin size="small" /> : null}
                    >
                      {comOption}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="备注">
                  {getFieldDecorator('remark', {})(
                    <Input placeholder="请输入备注" maxLength={100} />
                  )}
                </FormItem>
              </Col>
            </Row>
            <h3>浮动费率</h3>
            <Divider />
            <Row gutter={64}>
              <Col xl={{ span: 16 }} lg={{ span: 16 }} md={{ span: 16 }} sm={24}>
                <Button
                  style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
                  type="dashed"
                  onClick={this.addList}
                  icon={<PlusOutlined />}
                >
                  添加新时段
                </Button>
                <Table
                  rowKey={record => record.beginYm}
                  columns={columns}
                  dataSource={ratioList}
                  pagination={false} // 分页
                />
              </Col>
            </Row>
            {/* <h3>关联客户</h3>
                        <Divider />
                        <Button type="primary" onClick={this.add} style={{marginBottom:10}}>新增</Button>

                         <Row gutter={64}>
                                {
                                    costCenterList.map((item, index) =>
                                    (<Col {...colProps} key={item.costCenterId ? item.costCenterId : index}>
                                        <FormItem label="客户名称">
                                        {getFieldDecorator(item.costCenterId ? item.costCenterId : `list_${index}`, {
                                            rules: [{ required: true, message: '请输入关键字搜索客户名称'}],
                                        })(
                                            <Select showSearch labelInValue filterOption={false} onSearch={this.custName} style={{ width: '90%' }}  onSelect={(value)=>this.custNameSelect(value,index)} notFoundContent={fetching ? <Spin size="small" /> : null}
                                             placeholder="请输入关键字搜索客户名称"  >
											{comOption}
										 </Select>

                                      )}

                                        {costCenterList.length > 1 ? (
                                        <Icon   className="dynamic-delete-button"  type="minus-circle-o"
                                        onClick={() => this.delList(item.costCenterId)}   />
                                        ) : null}

                                        </FormItem>
                                    </Col>)
                                    )
                                }
                         </Row>  */}
          </Card>
          <Modal
            title="提醒"
            visible={visible}
            onOk={this.modalOk}
            onCancel={this.onCancel}
            okText="继续"
            cancelText="取消"
          >
            <p>启用后，‘所属大库、二级户编码、关联客户’将不可修改，确定启用吗？</p>
          </Modal>

          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={this.cancel}> 取消 </Button>
            <Button type="primary" onClick={this.submitAll} loading={btnState1}>
              提交
            </Button>
            <Button type="primary" onClick={this.showModal}>
              提交并启用
            </Button>
          </FooterToolbar>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default AdvancedForm;
